import { createRouter, createWebHistory } from "vue-router";
import loginRouters from "./login";
import manageRouters from "./manage/index";
import portalRouters from "./portal/index";

const whiteList = ["/login", "/register", "/find-pwd"];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...loginRouters, ...manageRouters, ...portalRouters],
});

router.beforeEach((to, from, next) => {
  if (
    !localStorage.getItem("ats-user-token") &&
    whiteList.indexOf(to.path) === -1
  ) {
    next({ path: "/login" });
  }
  if (to.path === "/") {
    if (localStorage.getItem("ats-user-userType") === "ADMIN") {
      next({ path: "/manage/index" });
    } else {
      next({ path: "/portal/home" });
    }
  }
  next();
});

export default router;
